/**
 * 真实医院运营数据服务
 * 基于真实医院运营数据模式生成的高度仿真数据
 */

// 时间工具函数
export const timeUtils = {
  now: () => new Date(),
  getTimeSlot: () => {
    const hour = new Date().getHours()
    if (hour >= 6 && hour < 12) return 'morning'
    if (hour >= 12 && hour < 18) return 'afternoon' 
    if (hour >= 18 && hour < 22) return 'evening'
    return 'night'
  },
  isWeekend: () => {
    const day = new Date().getDay()
    return day === 0 || day === 6
  },
  formatTime: (date: Date) => date.toLocaleTimeString('zh-CN', { hour12: false }),
  formatDate: (date: Date) => date.toLocaleDateString('zh-CN')
}

// 医院基础数据
export const hospitalData = {
  info: {
    name: '杭州市第一人民医院',
    level: '三级甲等',
    address: '浙江省杭州市西湖区古翠路300号',
    phone: '0571-87065701',
    totalBeds: 1200,
    dailyCapacity: 3000,
    founded: '1958年',
    staff: 2800
  },
  
  departments: [
    { id: 'emergency', name: '急诊科', floor: 'L1', capacity: 200, director: '陈医生', phone: '8801' },
    { id: 'internal', name: '内科', floor: 'L2', capacity: 150, director: '李医生', phone: '8802' },
    { id: 'surgery', name: '外科', floor: 'L3', capacity: 120, director: '王医生', phone: '8803' },
    { id: 'pediatrics', name: '儿科', floor: 'L2', capacity: 100, director: '张医生', phone: '8804' },
    { id: 'obstetrics', name: '妇产科', floor: 'L4', capacity: 80, director: '刘医生', phone: '8805' },
    { id: 'ophthalmology', name: '眼科', floor: 'L3', capacity: 60, director: '赵医生', phone: '8806' },
    { id: 'ent', name: '耳鼻喉科', floor: 'L3', capacity: 50, director: '孙医生', phone: '8807' },
    { id: 'dermatology', name: '皮肤科', floor: 'L2', capacity: 40, director: '周医生', phone: '8808' },
    { id: 'cardiology', name: '心血管科', floor: 'L5', capacity: 90, director: '吴医生', phone: '8809' },
    { id: 'neurology', name: '神经科', floor: 'L5', capacity: 70, director: '郑医生', phone: '8810' },
    { id: 'icu', name: 'ICU', floor: 'L6', capacity: 40, director: '朱医生', phone: '8811' },
    { id: 'or', name: '手术室', floor: 'L4', capacity: 12, director: '马医生', phone: '8812' }
  ],

  equipment: [
    { id: 'mri-01', name: 'MRI-01', type: 'MRI', location: '影像科B区', status: 'running', uptime: '95.2%', maintenance: '2024-01-08' },
    { id: 'ct-01', name: 'CT-01', type: 'CT', location: '影像科A区', status: 'running', uptime: '98.5%', maintenance: '2024-01-10' },
    { id: 'ct-02', name: 'CT-02', type: 'CT', location: '影像科A区', status: 'maintenance', uptime: '92.1%', maintenance: '2024-01-15' },
    { id: 'xray-01', name: 'X光机-01', type: 'X-Ray', location: 'L1放射科', status: 'running', uptime: '96.8%', maintenance: '2024-01-12' },
    { id: 'xray-02', name: 'X光机-02', type: 'X-Ray', location: 'L2放射科', status: 'running', uptime: '94.3%', maintenance: '2024-01-09' },
    { id: 'ultrasound-01', name: '超声波-01', type: 'Ultrasound', location: 'L3超声科', status: 'running', uptime: '97.2%', maintenance: '2024-01-11' },
    { id: 'ventilator-01', name: '呼吸机-01', type: 'Ventilator', location: 'ICU-01', status: 'running', uptime: '99.8%', maintenance: '2024-01-13' },
    { id: 'ventilator-02', name: '呼吸机-02', type: 'Ventilator', location: 'ICU-02', status: 'running', uptime: '99.5%', maintenance: '2024-01-14' },
    { id: 'or-system-01', name: '手术台-01', type: 'Surgery', location: '手术室01', status: 'running', uptime: '99.1%', maintenance: '2024-01-07' },
    { id: 'or-system-02', name: '手术台-02', type: 'Surgery', location: '手术室02', status: 'idle', uptime: '98.7%', maintenance: '2024-01-06' },
    { id: 'dialysis-01', name: '透析机-01', type: 'Dialysis', location: 'L5肾内科', status: 'running', uptime: '96.5%', maintenance: '2024-01-05' },
    { id: 'monitor-01', name: '监护仪-01', type: 'Monitor', location: 'ICU-01', status: 'running', uptime: '99.9%', maintenance: '2024-01-04' }
  ]
}

// 真实的医疗告警数据
export const generateRealisticAlerts = () => {
  const now = new Date()
  const timeSlot = timeUtils.getTimeSlot()
  const isWeekend = timeUtils.isWeekend()
  
  const alerts = [
    {
      id: 'ALT-001',
      type: 'crowding',
      severity: 'high',
      title: '急诊科患者聚集告警',
      location: '急诊科等候区',
      description: '等候区患者数量超出设计容量，当前密度3.2人/㎡',
      timestamp: new Date(now.getTime() - 15 * 60 * 1000).toISOString(),
      status: 'active',
      assignee: '急诊科值班医生',
      estimatedResolution: '15分钟',
      impact: '患者等待时间增加，满意度下降'
    },
    {
      id: 'ALT-002', 
      type: 'equipment',
      severity: 'medium',
      title: 'CT-02设备需要维护',
      location: '影像科A区',
      description: '设备连续运行18小时，温度传感器异常',
      timestamp: new Date(now.getTime() - 45 * 60 * 1000).toISOString(),
      status: 'in_progress',
      assignee: '医疗设备科',
      estimatedResolution: '2小时',
      impact: 'CT检查延迟，需调配其他设备'
    },
    {
      id: 'ALT-003',
      type: 'environment',
      severity: 'high',
      title: '手术室03温湿度异常',
      location: '手术室03',
      description: '温度28.5℃，湿度72%，超出手术标准',
      timestamp: new Date(now.getTime() - 8 * 60 * 1000).toISOString(),
      status: 'active',
      assignee: '手术室护士长',
      estimatedResolution: '10分钟',
      impact: '手术暂停，患者安全风险'
    },
    {
      id: 'ALT-004',
      type: 'supply',
      severity: 'medium',
      title: '药房抗生素库存不足',
      location: '中心药房',
      description: '头孢类抗生素库存仅剩3天用量',
      timestamp: new Date(now.getTime() - 2 * 60 * 60 * 1000).toISOString(),
      status: 'pending',
      assignee: '药剂科主任',
      estimatedResolution: '1天',
      impact: '影响处方开具，需紧急采购'
    }
  ]

  // 根据时间段调整告警数量和类型
  if (timeSlot === 'morning' || timeSlot === 'afternoon') {
    alerts.push({
      id: 'ALT-005',
      type: 'traffic',
      severity: 'low',
      title: '电梯等候时间过长',
      location: '1号患者电梯',
      description: '平均等候时间6.2分钟，超出标准值',
      timestamp: new Date(now.getTime() - 20 * 60 * 1000).toISOString(),
      status: 'monitoring',
      assignee: '保安部',
      estimatedResolution: '高峰期结束',
      impact: '患者体验下降，可能影响就诊流程'
    })
  }

  return alerts.slice(0, isWeekend ? 3 : alerts.length)
}

// 真实的患者流量数据 (基于实际医院数据模式)
export const generatePatientFlowData = () => {
  const hour = new Date().getHours()
  const isWeekend = timeUtils.isWeekend()
  const now = new Date()
  
  // 生成24小时数据
  const hourlyData = []
  for (let h = 0; h < 24; h++) {
    let baseFlow = 0
    
    // 模拟真实医院患者流量模式
    if (h >= 7 && h <= 9) baseFlow = isWeekend ? 120 : 180  // 早高峰
    else if (h >= 10 && h <= 11) baseFlow = isWeekend ? 100 : 150
    else if (h >= 14 && h <= 16) baseFlow = isWeekend ? 110 : 160  // 下午高峰
    else if (h >= 19 && h <= 21) baseFlow = isWeekend ? 80 : 120   // 晚间
    else if (h >= 22 || h <= 6) baseFlow = isWeekend ? 30 : 50     // 夜间
    else baseFlow = isWeekend ? 70 : 100
    
    // 添加随机波动 (±15%)
    const randomFactor = 0.85 + Math.random() * 0.3
    const finalFlow = Math.round(baseFlow * randomFactor)
    
    hourlyData.push({
      hour: h,
      time: `${h.toString().padStart(2, '0')}:00`,
      patients: finalFlow,
      emergency: Math.round(finalFlow * 0.12), // 急诊约占12%
      outpatient: Math.round(finalFlow * 0.78), // 门诊约占78%
      inpatient: Math.round(finalFlow * 0.10)   // 住院约占10%
    })
  }
  
  return hourlyData
}

// 生成部门实时数据
export const generateDepartmentData = () => {
  const timeSlot = timeUtils.getTimeSlot()
  const isWeekend = timeUtils.isWeekend()
  
  return hospitalData.departments.map(dept => {
    // 根据时间段和周末调整患者数量
    let basePatients = dept.capacity * 0.6 // 基础60%占用率
    
    // 时间段调整
    if (timeSlot === 'morning') basePatients *= 1.3
    else if (timeSlot === 'afternoon') basePatients *= 1.1
    else if (timeSlot === 'evening') basePatients *= 0.8
    else basePatients *= 0.4
    
    // 周末调整
    if (isWeekend) basePatients *= 0.7
    
    // 急诊科特殊处理
    if (dept.id === 'emergency') {
      basePatients = dept.capacity * (isWeekend ? 0.8 : 1.2)
    }
    
    const currentPatients = Math.floor(basePatients + (Math.random() - 0.5) * 20)
    const waitingTime = Math.max(5, Math.floor(30 + Math.random() * 60)) // 5-90分钟
    const utilizationRate = Math.min(100, Math.floor((currentPatients / dept.capacity) * 100))
    
    return {
      id: dept.id,
      name: dept.name,
      floor: dept.floor,
      capacity: dept.capacity,
      currentPatients: Math.max(0, currentPatients),
      waitingTime,
      utilizationRate,
      director: dept.director,
      phone: dept.phone,
      status: utilizationRate > 90 ? 'busy' : utilizationRate > 70 ? 'normal' : 'idle'
    }
  })
}

// 生成设备实时数据
export const generateEquipmentData = () => {
  const equipmentTypes = [
    { type: 'CT', count: 3, locations: ['L1 影像科', 'L2 影像科', 'L3 急诊影像'] },
    { type: 'MRI', count: 2, locations: ['L1 影像科', 'L2 影像科'] },
    { type: 'X光机', count: 8, locations: ['L1 影像科', 'L2 影像科', 'L3 骨科', 'L1 急诊科'] },
    { type: '超声设备', count: 12, locations: ['L2 超声科', 'L3 超声科', 'L4 妇产科', 'L2 内科'] },
    { type: '心电图机', count: 15, locations: ['L2 心内科', 'L3 心外科', 'L1 急诊科', 'L5 心血管科'] },
    { type: '呼吸机', count: 25, locations: ['L6 ICU', 'L1 急诊科', 'L4 手术室', 'L5 呼吸科'] },
    { type: '监护仪', count: 45, locations: ['L6 ICU', 'L1 急诊科', 'L4 手术室', 'L2-L5 各病区'] }
  ]
  
  const allEquipment: any[] = []
  let equipmentId = 1
  
  equipmentTypes.forEach(({ type, count, locations }) => {
    for (let i = 0; i < count; i++) {
      const location = locations[i % locations.length]
      const uptime = 85 + Math.random() * 14 // 85-99%
      const currentUtilization = Math.floor(Math.random() * 100)
      const maintenanceDate = new Date(Date.now() + (Math.random() * 30 - 15) * 24 * 60 * 60 * 1000)
      
      allEquipment.push({
        id: `equip_${equipmentId.toString().padStart(3, '0')}`,
        name: `${type}-${(i + 1).toString().padStart(2, '0')}`,
        type,
        location,
        status: Math.random() > 0.95 ? 'maintenance' : Math.random() > 0.85 ? 'busy' : 'idle',
        uptime: Math.floor(uptime),
        currentUtilization,
        maintenance: {
          lastDate: new Date(Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000),
          nextDate: maintenanceDate,
          status: maintenanceDate < new Date() ? 'overdue' : 'scheduled'
        },
        specifications: {
          manufacturer: ['西门子', '飞利浦', 'GE', '东软', '迈瑞'][Math.floor(Math.random() * 5)],
          model: `Model-${Math.floor(Math.random() * 9000) + 1000}`,
          year: 2018 + Math.floor(Math.random() * 6)
        }
      })
      
      equipmentId++
    }
  })
  
  return allEquipment
}

// 统一数据服务
export const realDataService = {
  // 获取所有实时数据
  getAllRealTimeData: () => ({
    timestamp: timeUtils.now(),
    hospital: hospitalData.info,
    alerts: generateRealisticAlerts(),
    patientFlow: generatePatientFlowData(),
    departments: generateDepartmentData(),
    equipment: generateEquipmentData(),
    kpis: {
      bedUtilization: {
        value: 89.5,
        target: 85,
        trend: 2.1,
        status: 'good',
        lastUpdate: new Date()
      },
      patientFlow: {
        value: 2441,
        target: 2200,
        trend: 156,
        status: 'excellent',
        lastUpdate: new Date()
      },
      equipmentEfficiency: {
        value: 96.2,
        target: 95,
        trend: -0.8,
        status: 'excellent',
        lastUpdate: new Date()
      },
      patientSatisfaction: {
        value: 94.2,
        target: 90,
        trend: 1.8,
        status: 'excellent',
        lastUpdate: new Date()
      },
      emergencyResponse: {
        value: 96.5,
        target: 95,
        trend: 0.5,
        status: 'excellent',
        lastUpdate: new Date()
      },
      averageWaitTime: {
        value: 25,
        target: 25,
        trend: -2.3,
        status: 'good',
        lastUpdate: new Date()
      }
    }
  }),
  
  // 模拟实时更新
  subscribeToUpdates: (callback: (data: any) => void, interval: number = 10000) => {
    const intervalId = setInterval(() => {
      callback(realDataService.getAllRealTimeData())
    }, interval)
    
    // 立即执行一次
    callback(realDataService.getAllRealTimeData())
    
    return () => clearInterval(intervalId)
  }
}

export default realDataService